package com.baizw.cultivation.module.admin.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.system.SystemUtil;
import com.baizw.cultivation.common.annotation.ExistInTable;
import com.baizw.cultivation.common.page.CustomPage;
import com.baizw.cultivation.common.properties.CultivationProperties;
import com.baizw.cultivation.common.response.ResultBean;
import com.baizw.cultivation.module.admin.entity.UserEntity;
import com.baizw.cultivation.module.admin.entity.vo.UserVO;
import com.baizw.cultivation.module.admin.service.UserService;
import com.baizw.cultivation.util.ImgUtil;
import com.baizw.cultivation.util.JwtUtil;
import com.baizw.cultivation.util.RedisUtil;
import com.baizw.cultivation.util.ShiroUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年04月30日 16:11:27
 */
@Validated
@RestController
@Api(tags = "用户管理")
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CultivationProperties properties;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取用户列表
     *
     * @return
     */
    @PostMapping("/list")
    @ApiOperation("分页查询用户列表")
    public ResultBean listUser(@RequestBody CustomPage page) {
        IPage<UserEntity> userPage = userService.getByPage(page);
        return ResultBean.ok().setResult(userPage);
    }

    /**
     * 根据ID获取用户详情
     *
     * @param userId 用户ID
     * @return
     */
    @ApiOperation("获取用户详情")
    @GetMapping({"/info/{userId}", "/info"})
    public ResultBean userDetail(@PathVariable(required = false) Long userId) {
        UserVO user = userService.getDetailById(ObjectUtil.isNull(userId) ? ShiroUtil.getUser().getId() : userId);
        return ResultBean.isTrue(ObjectUtil.isNotNull(user), "用户获取失败").setResult(user);
    }

    /**
     * 编辑用户
     *
     * @param user
     * @return
     */
    @PostMapping("/save_or_update")
    @ApiOperation("新增/更新用户信息")
    public ResultBean saveOrUpdate(@Valid @RequestBody UserEntity user) {
        user.setAvatar(ImgUtil.getDefaultAvatar());
        boolean result = userService.saveOrUpdate(user);
        return ResultBean.isTrue(result);
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/remove/{userId}")
    @ApiOperation("删除指定用户")
    public ResultBean removeUser(@PathVariable Long userId) {
        boolean result = userService.removeById(userId);
        return ResultBean.isTrue(result);
    }

    /**
     * 修改指定用户密码
     *
     * @param userId   用户ID
     * @param password 新密码
     * @return
     */
    @ApiOperation("修改指定用户密码")
    @PutMapping("/update/{userId}/{password}")
    public ResultBean modifyPassword(@Validated @PathVariable @ExistInTable(value = "t_user", message = "用户ID不存在") Long userId, @PathVariable String password) {
        UserEntity userEntity = userService.getById(userId);
        // 采用国密算法加密密码
        SymmetricCrypto sm4 = SmUtil.sm4(properties.sm4KeyBytes());
        String encryptHex = sm4.encryptHex(password);
        userEntity.setPassword(encryptHex);
        return ResultBean.isTrue(userService.updateById(userEntity));
    }

    @ApiOperation("获取用户头像")
    @GetMapping(value = "/avatar/{userId}", produces = MediaType.IMAGE_JPEG_VALUE)
    public void getUserAvatar(@PathVariable Long userId, HttpServletResponse response) {
        UserEntity userEntity = userService.getById(userId);
        byte[] avatar = userEntity.getAvatar();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            outputStream.write(avatar);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {

        }
    }

    @PostMapping("/update/avatar/{userId}")
    @ApiOperation("更新指定用户头像")
    public ResultBean updateAvatar(@PathVariable Long userId, @RequestParam("file") MultipartFile multipartFile) {
        UserEntity userEntity = userService.getById(userId);
        if (multipartFile.isEmpty()) {
            return ResultBean.error("头像不能为空");
        }
        try {
            byte[] fileBytes = multipartFile.getBytes();
            userEntity.setAvatar(fileBytes);
            userService.updateById(userEntity);
            return ResultBean.ok();
        } catch (IOException e) {
            return ResultBean.error();
        }
    }

    @GetMapping("/online")
    @ApiOperation("在线用户")
    public ResultBean onlineUsers() {
        Collection<String> keys = redisUtil.keys(JwtUtil.PREFIX_USER_TOKEN + "*");
        List<Object> collect = keys.parallelStream().map(x -> redisUtil.get(x)).map(x -> JwtUtil.getUserName(x.toString())).collect(Collectors.toList());
        return ResultBean.ok(collect);
    }
}
